package com.lihao.demo1.view;


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.HorizontalScrollView;


import com.lihao.demo1.R;

import java.util.Timer;
import java.util.TimerTask;

public class MainScrollView extends HorizontalScrollView {

    private int mFactor;
    private int mBitmapRes;
    private Bitmap mBitmap;
    private Rect mBackgroundOrginalRect;
    private RectF mBackgroundNewRect;
    private float mBackgroundX = 0;
    private Timer scrollTimer;
    private TimerTask scrollerSchedule;
    private int scrollPos = 0;
    private int oldscrollpos = -1;
    private boolean mRightPostion = false;

    public interface ITouchMove {
        public void move(float value);
        public void moveOver();
    }


    private ITouchMove mITouchMove;

    public MainScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.MainScrollView);
        mFactor = a.getInteger(R.styleable.MainScrollView_factor, 3);

        if (mFactor < 1) {
            throw new IllegalArgumentException(
                    "Factor value can't be less than 1");
        }

        mBitmapRes = a.getResourceId(R.styleable.MainScrollView_image, -1);

        a.recycle();
    }

    public void initPos(boolean right){
        mRightPostion = right;
    }

    public void setTouchListener(ITouchMove touchMove) {
        mITouchMove = touchMove;
    }

    public MainScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.MainScrollView);
        mFactor = a.getInteger(R.styleable.MainScrollView_factor, 3);

        if (mFactor < 1) {
            throw new IllegalArgumentException(
                    "Factor value can't be less than 1");
        }

        mBitmapRes = a.getResourceId(R.styleable.MainScrollView_image, -1);
        if (mBitmapRes > -1) {

            Drawable drawable = getResources().getDrawable(mBitmapRes);

            if (drawable instanceof BitmapDrawable) {
                mBitmap = ((BitmapDrawable) drawable).getBitmap();
            }
        }
        a.recycle();
    }

    public MainScrollView(Context context) {
        super(context);
        init();
    }

    private void init() {

    }

    @Override
    protected void onScrollChanged(int x, int y, int oldx, int oldy) {
        // TODO Auto-generated method stub
        super.onScrollChanged(x, y, oldx, oldy);
        float bX = mBackgroundX;
        mBackgroundX += (oldx - x) / 3;
        if (bX != mBackgroundX) {
            if (mBackgroundX > 0) {
                mBackgroundX = 0;
            }
            //Log.e("Scroll", "--------------:" + mBackgroundX);
            if (mITouchMove != null) {
                mITouchMove.move(x - oldx);
            }
            processBitmap();
        }
    }

    @Override
    public boolean arrowScroll(int direction) {
        // TODO Auto-generated method stub
        return super.arrowScroll(direction);
    }

    @Override
    public void scrollTo(int x, int y) {
        super.scrollTo(x, y);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        processBitmap();
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {

        if (mBitmap != null) {

            int save = canvas.save();
            Rect rect = canvas.getClipBounds();
            canvas.translate(rect.left, rect.top);
            //Log.d("Scroll", "--------XXXXXXXXXXXXXXXXXXxxx------:" + mBackgroundX);
            canvas.drawBitmap(mBitmap, mBackgroundOrginalRect, new RectF(
                    mBackgroundX, 0, mBackgroundNewRect.right + mBackgroundX,
                    mBackgroundNewRect.bottom), null);

            canvas.restoreToCount(save);

        }

        super.dispatchDraw(canvas);
    }

    private void processBitmap() {
        int w = getWidth();
        int h = getHeight();

        boolean isDrawable = false;

//        if (mBitmapRes > -1) {
//
//            Drawable drawable = getResources().getDrawable(mBitmapRes);
//
//            if (drawable instanceof BitmapDrawable) {
//                mBitmap = ((BitmapDrawable) drawable).getBitmap();
//            } else {
//                isDrawable = true;
//
//                mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
//                Canvas canvas = new Canvas(mBitmap);
//
//                drawable.setBounds(getLeft(), getTop(), getRight(), getBottom());
//
//                drawable.draw(canvas);
//
//            }
//        }

        if (mBitmap == null || w == 0 || h == 0) {
            return;
        }

        float count = 1;

        int imgWidth = mBitmap.getWidth();
        int imgHeight = mBitmap.getHeight();

        float ratio = (float) imgWidth / (float) imgHeight;

        float width = w * (mFactor);
        float height = h;//(isDrawable ? imgHeight : width / ratio);

        mBackgroundOrginalRect = new Rect(0, 0, imgWidth, imgHeight);
        mBackgroundNewRect = new RectF(0, 0, width, height);

        Rect sizeRect = new Rect(0, 0, w * mFactor, h);

    }

    public void setFlowImage(Bitmap bitmap) {
        mBitmap = bitmap;
        processBitmap();
    }

    public void setFlowImage(int resId) {
        mBitmap = BitmapFactory.decodeResource(getResources(), resId);
        processBitmap();
        invalidate();
        requestLayout();
    }


    public void setFlowFactor(int factor) {
        if (factor < 1) {
            throw new IllegalArgumentException(
                    "Factor value can't be less than 1");
        }
        this.mFactor = factor;
        processBitmap();
        invalidate();
        requestLayout();
    }

    public void startAutoScrolling() {
        if (scrollTimer == null) {
            scrollTimer = new Timer();
            final Runnable Timer_Tick = new Runnable() {
                public void run() {
                    moveScrollViewRightToLeft();
                }
            };

            if (scrollerSchedule != null) {
                scrollerSchedule.cancel();
                scrollerSchedule = null;
            }
            scrollerSchedule = new TimerTask() {
                @Override
                public void run() {
                    //((Activity) getContext()).runOnUiThread(Timer_Tick);
                    MainScrollView.this.post(Timer_Tick);
                }
            };

            scrollTimer.schedule(scrollerSchedule, 1, 1);
        }
    }

    public void moveScrollViewRightToLeft() {
        scrollPos = (int) (getScrollX() - 2.0);
        //Log.d("Scroll", "--------moveScrollViewRightToLeft------scrollPos:" + scrollPos);
        scrollTo(scrollPos, 0);
        if (scrollPos != oldscrollpos) {
            oldscrollpos = scrollPos;
        } else {
            if (scrollerSchedule != null) {
                scrollerSchedule.cancel();
                scrollerSchedule = null;
            }
            if (mITouchMove != null) {
                mITouchMove.moveOver();
            }
            return;
        }
    }

    public void release(){
        if (scrollerSchedule != null) {
            scrollerSchedule.cancel();
            scrollerSchedule = null;
        }
    }

}
